﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Media.Imaging;
using System.Windows;
using System.Windows.Media;
using System.IO;
using System.Windows.Shapes;

namespace Bookvar.UI
{
    public static class MapThumbnailUtility
    {
        static List<string> filesToDispose = new List<string>();
        public static string GenerateMapThumbnail(MindMapPanel mapCanvas, double horizontalOffset, double verticalOffset, string fileName)
        {
            DisposeOldFiles();
            int pixelWidth = (int)mapCanvas.ActualWidth;
            int pixelHeight = (int)mapCanvas.ActualHeight;
            string tempFileName = fileName;
            //Console.WriteLine(mapCanvas.SurroundingRectangle);
            if (pixelHeight > 0 && pixelWidth > 0)
            {
                ScaleTransform scaleTransform = null;
                ScaleTransform normalTransform = null;
                TransformGroup group = mapCanvas.LayoutTransform as TransformGroup;
                if (group != null)
                {
                    foreach (Transform transformaion in group.Children)
                    {
						ScaleTransform castTransformation = transformaion as ScaleTransform;
                        if (castTransformation != null)
                        {
                            scaleTransform = castTransformation;                            
                            
                            //original = new TransformedBitmap(source, scaleTransformReversed);
                        }
                    }
                    if (scaleTransform != null)
                    {
                        group.Children.Remove(scaleTransform);
                        normalTransform = new ScaleTransform(1, 1);
                        group.Children.Add(normalTransform);
                        mapCanvas.UpdateLayout();
                    }
                }
                //if (scaleTransform != null)
                //{
                //    mapCanvas
                //}

                RenderTargetBitmap source = new RenderTargetBitmap(pixelWidth, pixelHeight, 96, 96, PixelFormats.Pbgra32);
                //source.
                source.Render(mapCanvas);
                if (group != null && normalTransform != null)
                {
                    group.Children.Remove(normalTransform);
                    group.Children.Add(scaleTransform);
                    mapCanvas.UpdateLayout();

                }
                Rect rectangle = mapCanvas.SurroundingRectangle;
                //Int32Rect rect = new Int32Rect(0, 0, 540, 280);
                Int32Rect rect;
                if (rectangle.Width < 200 && rectangle.Height < 200)
                {
                    rect = new Int32Rect((int)rectangle.X - (int)horizontalOffset - (200 - (int)rectangle.Width) / 2, (int)rectangle.Y - (int)verticalOffset - (200 - (int)rectangle.Height) / 2, 200, 200);
                }
                else
                {
                    rect = new Int32Rect((int)rectangle.X - (int)horizontalOffset, (int)rectangle.Y - (int)verticalOffset, (int)rectangle.Width, (int)rectangle.Height);
                }

                if (rect.X < 0 || rect.Y < 0 || (rect.X + rect.Width > source.Width) || (rect.Y + rect.Height> source.Height) )
                {
                    return String.Empty;
                }
                CroppedBitmap cropped = new CroppedBitmap(source, rect);

                if (cropped.CanFreeze)
                {
                    cropped.Freeze();

                }
                double maxSize = Math.Max(rect.Width, rect.Height);
                double scale = 200 / maxSize;
                TransformedBitmap scaled = new TransformedBitmap(cropped, new ScaleTransform(scale, scale));

                if (scaled.CanFreeze)
                {
                    scaled.Freeze();
                }
                
                BitmapFrame item = BitmapFrame.Create(scaled);

                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(item);
                encoder.Interlace = PngInterlaceOption.Default;
                tempFileName = System.IO.Path.GetTempFileName();

                try
                {
                    using (FileStream stream = new FileStream(tempFileName, FileMode.OpenOrCreate))
                    {
                        encoder.Save(stream);
                    }
                }
                catch (IOException)
                {
                    return null;
                }
            }
            filesToDispose.Add(fileName);
            return tempFileName;

            //return cropped;
            //return result;
        }

        private static void DisposeOldFiles()
        {
            List<string> toRemove = new List<string>();
            foreach (string fileToDispose in filesToDispose)
            {
                try
                {
                    if (File.Exists(fileToDispose))
                    {
                        File.Delete(fileToDispose);
                    }
                }
                catch (IOException)
                {
                    continue;
                }
                toRemove.Add(fileToDispose);
            }
            foreach (string file in toRemove)
            {
                filesToDispose.Remove(file);
            }
        }

        public static string GenerateMapImage(FrameworkElement mapCanvas, string fileName)
        {

            int pixelWidth = (int)mapCanvas.ActualWidth;
            int pixelHeight = (int)mapCanvas.ActualHeight;
            string tempFileName = String.Empty;

            if (pixelHeight > 0 && pixelWidth > 0)
            {
                RenderTargetBitmap source = new RenderTargetBitmap(pixelWidth, pixelHeight, 96, 96, PixelFormats.Pbgra32);
                source.Render(mapCanvas);

                BitmapFrame item = BitmapFrame.Create(source);

                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(item);
                encoder.Interlace = PngInterlaceOption.Default;

                tempFileName = System.IO.Path.GetTempFileName();
                using (FileStream stream = new FileStream(tempFileName, FileMode.OpenOrCreate))
                {
                    encoder.Save(stream);
                }
                filesToDispose.Add(fileName);
            }
            return tempFileName;
        }


    }
}
